from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app01 import models
from app01.utils.form import UserInfoModelForm
from app01.utils.pagination import Pagination


def user_list(request):
    """用户列表"""
    if request.session.get("info")["level"] == 3:
        return render(request, 'error.html')

    # 去数据库中获取所有的用户列表
    #  [对象,对象,对象]

    # 构造搜索
    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["name__contains"] = search_data

    # 根据搜索条件去数据库获取
    queryset = models.UserInfo.objects.filter(**data_dict).order_by('-id')

    # 实例化分页对象
    page_object = Pagination(request, queryset)

    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html(),  # 生成页码
        "search_data": search_data,
    }
    return render(request, 'user_list.html', context)


def user_add(request):
    """增加用户"""
    if request.session.get("info")["level"] == 3:
        return render(request, 'error.html')

    if request.method == 'GET':
        form = UserInfoModelForm()
        return render(request, 'user_add.html', {"form": form})

    # 获取用户POST提交过来的数据
    form = UserInfoModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        # 重定向回部门列表
        return redirect('/user/list/')

    return render(request, 'user_add.html', {"form": form})


def user_delete(request):
    """ 删除用户 """
    if request.session.get("info")["level"] == 3:
        return render(request, 'error.html')

    # 获取ajax发送的ID http://127.0.0.1:8000/user/delete/?nid=1
    uid = request.GET.get('uid')

    # 删除前确认数据是否存在
    exists = models.UserInfo.objects.filter(id=uid).exists()
    if not exists:
        # 如果数据不存在返回错误信息
        return JsonResponse({"status": False, 'error': "删除失败，数据不存在。"})
    # 如果存在进行删除操作
    models.UserInfo.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


def user_edit(request, nid):
    """ 编辑用户 """
    if request.session.get("info")["level"] == 3:
        return render(request, 'error.html')

    row_object = models.UserInfo.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = UserInfoModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})

    # 修改数据时要加上instance属性并用原数据赋值
    # 否则就会只根据用户提供的数据在数据库进行新数据的创建，而不是在原数据的基础上进行修改
    form = UserInfoModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据，如果想要再用户输入以外增加一点值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/user/list/')
    # 如果数据校验失败就会带着错误信息返回编辑界面
    return render(request, 'user_edit.html', {"form": form})


@csrf_exempt
def info_list(request):
    if request.method == "GET":
        return render(request, 'info_list.html')

    user_info = request.session.get('info')
    nid = user_info["id"]

    last_time = models.Record.objects.filter(user_info=nid).order_by('-id').first()

    last_record = {}
    if not last_time:
        last_record["signin_time"] = "暂无签到记录"
    else:
        last_record["signin_time"] = last_time.signin_time

    row_object = models.UserInfo.objects.filter(id=nid).first()

    data = {
        "student_id": row_object.sid,
        "student_name": row_object.name,
        "student_password": row_object.password,
        "student_gender": row_object.get_gender_display(),
        "student_department": row_object.depart.title,
        "student_ip": request.META.get('REMOTE_ADDR'),
        "last_signin_time": last_record["signin_time"],
    }
    result = {
        "status": True,
        "data": data
    }
    return JsonResponse(result)
